# -*- coding: utf-8 -*-
# @Time : 2019/2/16 10:37
# @Author : Chilson

import json
import requests


def wechat_alert(error_string, corp_id, corp_secret, party_id, agent_id):
    """微信公众号报警

    Args:
        corp_id: str 公司ID
        corp_secret: str 秘钥
        error_string: str 报警内容
        party_id: str 部门ID
        agent_id: int 应用ID

    Returns:
         send_message.json(): json 报警返回结果
    """
    base_url = 'https://qyapi.weixin.qq.com/cgi-bin/'
    # 公司id
    corp_id = corp_id
    # 应用秘钥
    corp_secret = corp_secret
    # 申请token
    get_token_url = base_url + \
        'gettoken?corpid=%s&corpsecret=%s' % (corp_id, corp_secret)
    token = requests.get(get_token_url).json()['access_token']
    # 部门ID
    party_id = party_id
    # 应用ID
    agent_id = agent_id
    # 告警信息
    send_url = base_url + 'message/send?access_token=%s' % token
    send_data = {'touser': '', 'toparty': party_id, 'totag': '', 'msgtype': 'text', 'agentid': agent_id,
                 'text': {'content': error_string}, 'safe': 0}
    # 字典需转成json，不能解读字典
    send_data = json.dumps(send_data)
    send_message = requests.post(send_url, send_data)
    return send_message.json()
